#include "dataaccessor.h"
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include "dbconnectionpool.h"


bool DataAccessor::findPasswordAndSaltByUserId(const int& userId, QByteArray& password, QString& salt)
{
    // 获取连接池实例及数据库连接
    auto dbPool = DBConnectionPool::GetInstance();
    QSqlDatabase db = dbPool->AcquireConnection();

    // 1. 直接判断数据库是否打开
    if (!db.isOpen())
    {
        dbPool->ReleaseConnection(db);
        return false;
    }

    // 2. 准备查询语句 取出盐值和正确密码
    QSqlQuery query(db);
    query.prepare("select salt, password from user_static_info where user_id = :userId");
    query.bindValue(":userId", userId);

    // 3. 执行查询
    if (!query.exec())
    {
        qWarning() << "Query execution failed:" << query.lastError().text();
        dbPool->ReleaseConnection(db);
        return false;
    }

    // 4. 获取查询结果
    bool found = false;
    while (query.next())
    {
        salt = query.value("salt").toString();
        password = query.value("password").toByteArray();
        found = true;
    }
    // 没有结果集，直接返回false
    if (!found)
    {
        dbPool->ReleaseConnection(db);
        return false; // 如果没有任何记录，返回 false
    }

    // 5. 执行成功，返回true
    dbPool->ReleaseConnection(db);
    return true;
}

bool DataAccessor::findOnlineStatusByUserId(const int& userId, bool& onlineStatus)
{
    // 获取连接池实例及数据库连接
    auto dbPool = DBConnectionPool::GetInstance();
    QSqlDatabase db = dbPool->AcquireConnection();

    // 1. 直接判断数据库是否打开
    if (!db.isOpen())
    {
        dbPool->ReleaseConnection(db);
        return false;
    }

    // 2. 准备查询语句
    QSqlQuery query(db);
    query.prepare("select online_status from user_dynamic_info where user_id = :userId");
    query.bindValue(":userId", userId);

    // 3. 执行查询
    if (!query.exec())
    {
        qWarning() << "Query execution failed:" << query.lastError().text();
        dbPool->ReleaseConnection(db);
        return false;
    }

    // 4. 获取查询结果
    bool found = false;
    while (query.next())
    {
        onlineStatus = query.value("online_status").toBool();
        found = true;
    }
    // 没有结果集，直接返回false
    if (!found)
    {
        dbPool->ReleaseConnection(db);
        return false; // 如果没有任何记录，返回 false
    }

    // 5. 执行成功，返回true
    dbPool->ReleaseConnection(db);
    return true;
}

bool DataAccessor::findRegisteredUserByEmail(const QString& email, bool& isRegistered)
{
    // 获取连接池实例及数据库连接
    auto dbPool = DBConnectionPool::GetInstance();
    QSqlDatabase db = dbPool->AcquireConnection();

    // 1. 直接判断数据库是否打开
    if (!db.isOpen())
    {
        dbPool->ReleaseConnection(db);
        return false;
    }

    // 2. 准备查询语句
    QSqlQuery query(db);
    query.prepare("select count(*) from user_static_info where email = :email");
    query.bindValue(":email", email);

    // 3. 执行查询
    if (!query.exec())
    {
        qWarning() << "Query execution failed:" << query.lastError().text();
        dbPool->ReleaseConnection(db);
        return false;
    }

    // 4. 获取查询结果
    bool found = false;
    while (query.next())
    {
        int count = query.value(0).toInt();
        if (count == 0) // 没取到结果表示没有注册过
        {
            isRegistered = false;
            return true;    // 返回值有效
        }
        else if (count != 1)    // 该邮箱已经被莫名其妙注册一堆了
        {
            return false;   // 返回值无效
        }
        isRegistered = true;    // 注册过一次
        found = true;
    }
    // 没有结果集，直接返回false
    if (!found)
    {
        dbPool->ReleaseConnection(db);
        return false; // 如果没有任何记录，返回 false
    }
    // 5. 执行成功，返回true
    dbPool->ReleaseConnection(db);
    return true;

}

bool DataAccessor::insertNewUserStaticInfo(const QString& email, const QString& nickname,
                                     const QByteArray& password, const QString& salt)
{
    // 获取连接池实例及数据库连接
    auto dbPool = DBConnectionPool::GetInstance();
    QSqlDatabase db = dbPool->AcquireConnection();

    // 1. 直接判断数据库是否打开
    if (!db.isOpen())
    {
        dbPool->ReleaseConnection(db);
        return false;
    }

    // 2. 准备查询语句
    QSqlQuery query(db);
    query.prepare("INSERT INTO user_static_info (email, nickname, password, salt) "
                  "VALUES (:email, :nickname, :password, :salt)");
    query.bindValue(":email", email);
    query.bindValue(":nickname", nickname);
    query.bindValue(":password", password);
    query.bindValue(":salt", salt);

    // 3. 执行查询
    if (!query.exec())
    {
        qWarning() << "Query execution failed:" << query.lastError().text();
        dbPool->ReleaseConnection(db);
        return false;
    }

    dbPool->ReleaseConnection(db);
    return true;
}

bool DataAccessor::insertNewUserDynamicInfo(const int& userId)
{
    // 获取连接池实例及数据库连接
    auto dbPool = DBConnectionPool::GetInstance();
    QSqlDatabase db = dbPool->AcquireConnection();

    // 1. 直接判断数据库是否打开
    if (!db.isOpen())
    {
        dbPool->ReleaseConnection(db);
        return false;
    }

    // 2. 准备查询语句
    QSqlQuery query(db);
    query.prepare("insert into user_dynamic_info (user_id) value (:userId)");
    query.bindValue(":userId", userId);


    // 3. 执行查询
    if (!query.exec())
    {
        qWarning() << "Query execution failed:" << query.lastError().text();
        dbPool->ReleaseConnection(db);
        return false;
    }

    dbPool->ReleaseConnection(db);
    return true;
}

bool DataAccessor::updateUserOnlineStatus(const int& userId, const bool& onlineStatus)
{
    // 获取连接池实例及数据库连接
    auto dbPool = DBConnectionPool::GetInstance();
    QSqlDatabase db = dbPool->AcquireConnection();

    // 1. 直接判断数据库是否打开
    if (!db.isOpen())
    {
        dbPool->ReleaseConnection(db);
        return false;
    }

    // 2. 准备查询语句
    QSqlQuery query(db);
    query.prepare("update user_dynamic_info set online_status = :onlineStatus where user_id = :userId;");
    query.bindValue(":onlineStatus", onlineStatus);
    query.bindValue(":userId", userId);

    // 3. 执行查询
    if (!query.exec())
    {
        qWarning() << "Query execution failed:" << query.lastError().text();
        dbPool->ReleaseConnection(db);
        return false;
    }

    // 打印原始 SQL
    // qDebug() << "Original SQL:" << query.lastQuery();

    dbPool->ReleaseConnection(db);
    return true;
}

// 在用户动态信息表中，修改全部用户在线状态
bool DataAccessor::updateAllUserOnlineStatus(const bool& onlineStatus)
{
    // 获取连接池实例及数据库连接
    auto dbPool = DBConnectionPool::GetInstance();
    QSqlDatabase db = dbPool->AcquireConnection();

    // 1. 直接判断数据库是否打开
    if (!db.isOpen())
    {
        dbPool->ReleaseConnection(db);
        return false;
    }

    // 2. 准备查询语句
    QSqlQuery query(db);
    query.prepare("update user_dynamic_info set online_status = :onlineStatus;");
    query.bindValue(":onlineStatus", onlineStatus);

    // 3. 执行查询
    if (!query.exec())
    {
        qWarning() << "Query execution failed:" << query.lastError().text();
        dbPool->ReleaseConnection(db);
        return false;
    }

    dbPool->ReleaseConnection(db);
    return true;
}

bool DataAccessor::findUserIdByEmail(const QString& email, int& userId)
{
    // 获取连接池实例及数据库连接
    auto dbPool = DBConnectionPool::GetInstance();
    QSqlDatabase db = dbPool->AcquireConnection();

    // 1. 直接判断数据库是否打开
    if (!db.isOpen())
    {
        dbPool->ReleaseConnection(db);
        return false;
    }

    // 2. 准备查询语句
    QSqlQuery query(db);
    query.prepare("select user_id from user_static_info where email = :email");
    query.bindValue(":email", email);

    // 3. 执行查询
    if (!query.exec()) {
        qWarning() << "Query execution failed:" << query.lastError().text();
        dbPool->ReleaseConnection(db);
        return false;
    }

    // 4. 获取查询结果
    bool found = false;
    while (query.next())
    {
        userId = query.value("user_id").toInt();
        found = true;
    }
    // 没有结果集，直接返回false
    if (!found)
    {
        dbPool->ReleaseConnection(db);
        return false; // 如果没有任何记录，返回 false
    }

    // 5. 执行成功，返回true
    dbPool->ReleaseConnection(db);
    return true;
}

bool DataAccessor::findUserInfoByUserId(const int& userId, QString& nickname)
{
    // 获取连接池实例及数据库连接
    auto dbPool = DBConnectionPool::GetInstance();
    QSqlDatabase db = dbPool->AcquireConnection();

    // 1. 直接判断数据库是否打开
    if (!db.isOpen())
    {
        dbPool->ReleaseConnection(db);
        return false;
    }

    // 2. 准备查询语句
    QSqlQuery query(db);
    query.prepare("select nickname from user_static_info where user_id = :userId");
    query.bindValue(":userId", userId);

    // 3. 执行查询
    if (!query.exec()) {
        qWarning() << "Query execution failed:" << query.lastError().text();
        dbPool->ReleaseConnection(db);
        return false;
    }

    // 4. 获取查询结果
    bool found = false;
    while (query.next())
    {
        nickname = query.value("nickname").toString();
        found = true;
    }
    // 没有结果集，直接返回false
    if (!found)
    {
        dbPool->ReleaseConnection(db);
        return false; // 如果没有任何记录，返回 false
    }

    // 5. 执行成功，返回true
    dbPool->ReleaseConnection(db);
    return true;
}


// 在好友关系申请表中，通过两个用户的Id查看是否已经有了待审核的申请
bool DataAccessor::findUnverifiedApplication(const int& userId, const int& friendId, bool& existed)
{
    // 获取连接池实例及数据库连接
    auto dbPool = DBConnectionPool::GetInstance();
    QSqlDatabase db = dbPool->AcquireConnection();

    // 1. 直接判断数据库是否打开
    if (!db.isOpen())
    {
        dbPool->ReleaseConnection(db);
        return false;
    }

    // 2. 准备查询语句
    QSqlQuery query(db);
    query.prepare("select count(*) from friendship_verify_info "
                  "where user_id = :userId and friend_id = :friendId and status = 0;");
    query.bindValue(":userId", userId);
    query.bindValue(":friendId", friendId);


    // 3. 执行查询
    if (!query.exec())
    {
        qWarning() << "Query execution failed:" << query.lastError().text();
        dbPool->ReleaseConnection(db);
        return false;
    }

    // 4. 获取查询结果
    bool found = false;
    while (query.next())
    {
        int count = query.value(0).toInt();
        if (count == 0) // 没取到结果表示没有已经申请但还没有验证的消息
        {
            existed = false;
            return true;    // 返回值有效
        }
        else if (count != 1)    // 该邮箱已经被莫名其妙注册一堆了
        {
            return false;   // 返回值无效
        }
        existed = true;    // 之前申请过
        found = true;
    }
    // 没有结果集，直接返回false
    if (!found)
    {
        dbPool->ReleaseConnection(db);
        return false; // 如果没有任何记录，返回 false
    }
    // 5. 执行成功，返回true
    dbPool->ReleaseConnection(db);
    return true;
}

// 在好友关系申请表中，修改已经有了的请求信息（验证消息）
bool DataAccessor::updateUnverifiedApplication(const int& userId, const int& friendId,
                                               const QString& alias, const QString& verifyInfo)
{
    // 获取连接池实例及数据库连接
    auto dbPool = DBConnectionPool::GetInstance();
    QSqlDatabase db = dbPool->AcquireConnection();

    // 1. 直接判断数据库是否打开
    if (!db.isOpen())
    {
        dbPool->ReleaseConnection(db);
        return false;
    }

    // 2. 准备查询语句
    QSqlQuery query(db);
    query.prepare("update friendship_verify_info set alias = :alias, verify_info = :verifyInfo "
                  "where user_id = :userId and friend_id = :friendId;");
    query.bindValue(":alias", alias);
    query.bindValue(":verifyInfo", verifyInfo);
    query.bindValue(":userId", userId);
    query.bindValue(":friendId", friendId);


    // 3. 执行查询
    if (!query.exec())
    {
        qWarning() << "Query execution failed:" << query.lastError().text();
        dbPool->ReleaseConnection(db);
        return false;
    }

    dbPool->ReleaseConnection(db);
    return true;
}

bool DataAccessor::insertApplication(const int& userId, const int& friendId,
                              const QString& alias, const QString& verifyInfo)
{
    // 获取连接池实例及数据库连接
    auto dbPool = DBConnectionPool::GetInstance();
    QSqlDatabase db = dbPool->AcquireConnection();

    // 1. 直接判断数据库是否打开
    if (!db.isOpen())
    {
        dbPool->ReleaseConnection(db);
        return false;
    }

    // 2. 准备查询语句
    QSqlQuery query(db);
    query.prepare("insert into friendship_verify_info (user_id, friend_id, alias, verify_info) "
                  "value (:userId, :friendId, :alias, :verifyInfo)");
    query.bindValue(":userId", userId);
    query.bindValue(":friendId", friendId);
    query.bindValue(":alias", alias);
    query.bindValue(":verifyInfo", verifyInfo);


    // 3. 执行查询
    if (!query.exec())
    {
        qWarning() << "Query execution failed:" << query.lastError().text();
        dbPool->ReleaseConnection(db);
        return false;
    }

    dbPool->ReleaseConnection(db);
    return true;
}

// 在好友关系申请表中，通过userId查询所有好友申请（所有向user申请添加好友的请求）
bool DataAccessor::findFriendApplicationsByUserId(const int& userId,
                                                  QVector<NewFriendApplicationQueryResult>& results)
{
    // 获取连接池实例及数据库连接
    auto dbPool = DBConnectionPool::GetInstance();
    QSqlDatabase db = dbPool->AcquireConnection();

    // 1. 直接判断数据库是否打开
    if (!db.isOpen())
    {
        dbPool->ReleaseConnection(db);
        return false;
    }

    // 2. 准备查询语句
    QSqlQuery query(db);
    QString sql = "SELECT ft.id, ft.user_id, ft.friend_id, ut.nickname, ft.verify_info, ft.create_at"
                  " FROM friendship_verify_info AS ft"
                  " JOIN user_static_info AS ut ON ft.friend_id = ut.user_id"
                  " WHERE ft.friend_id = :friendId AND ft.status = 0;";
    query.prepare(sql);
    query.bindValue(":friendId", userId);

    // 3. 执行查询
    if (!query.exec()) {
        qWarning() << "Query execution failed:" << query.lastError().text();
        dbPool->ReleaseConnection(db);
        return false;
    }

    // 4. 获取查询结果
    while (query.next())
    {
        NewFriendApplicationQueryResult record;
        record.receiverId = query.value("friend_id").toInt();
        record.applicantId = query.value("user_id").toInt();
        record.nickname = query.value("nickname").toString();
        record.verifyInfo = query.value("verify_info").toString();
        record.applyTime = query.value("create_at").toDateTime();
        record.id = query.value("id").toInt();
        results.append(record);
    }


    // 5. 执行成功，返回true
    dbPool->ReleaseConnection(db);
    return true;
}

// bool DataAccessor::updateFriendApplicationStatus(const int& status, const int& userId, const int& friendId)
// {
//     // 获取连接池实例及数据库连接
//     auto dbPool = DBConnectionPool::GetInstance();
//     QSqlDatabase db = dbPool->AcquireConnection();

//     // 1. 直接判断数据库是否打开
//     if (!db.isOpen())
//     {
//         dbPool->ReleaseConnection(db);
//         return false;
//     }

//     // 2. 准备查询语句
//     QSqlQuery query(db);
//     query.prepare("update friendship_verify_info set status = :status "
//                   "where user_id = :userId and friend_id = :friendId;");
//     query.bindValue(":status", status);
//     query.bindValue(":userId", userId);
//     query.bindValue(":friendId", friendId);


//     // 3. 执行查询
//     if (!query.exec())
//     {
//         qWarning() << "Query execution failed:" << query.lastError().text();
//         dbPool->ReleaseConnection(db);
//         return false;
//     }


//     dbPool->ReleaseConnection(db);
//     return true;
// }

bool DataAccessor::updateFriendApplicationStatusById(const int& id, const int status)
{
    // 获取连接池实例及数据库连接
    auto dbPool = DBConnectionPool::GetInstance();
    QSqlDatabase db = dbPool->AcquireConnection();

    // 1. 直接判断数据库是否打开
    if (!db.isOpen())
    {
        dbPool->ReleaseConnection(db);
        return false;
    }

    // 2. 准备查询语句
    QSqlQuery query(db);
    query.prepare("update friendship_verify_info set status = :status "
                  "where id = :id;");
    query.bindValue(":status", status);
    query.bindValue(":id", id);


    // 3. 执行查询
    if (!query.exec())
    {
        qWarning() << "Query execution failed:" << query.lastError().text();
        dbPool->ReleaseConnection(db);
        return false;
    }


    dbPool->ReleaseConnection(db);
    return true;
}

bool DataAccessor::findUserIdsAndAliasByRecordId(const int& serverId, int& userId, int& friendId, QString& alias)
{
    // 获取连接池实例及数据库连接
    auto dbPool = DBConnectionPool::GetInstance();
    QSqlDatabase db = dbPool->AcquireConnection();

    // 1. 直接判断数据库是否打开
    if (!db.isOpen())
    {
        dbPool->ReleaseConnection(db);
        return false;
    }

    // 2. 准备查询语句
    QSqlQuery query(db);
    QString sql = "select user_id, friend_id, alias "
                  "from friendship_verify_info "
                  "where id = :serverId ";
    query.prepare(sql);
    query.bindValue(":serverId", serverId);


    // 3. 执行查询
    if (!query.exec()) {
        qWarning() << "Query execution failed:" << query.lastError().text();
        dbPool->ReleaseConnection(db);
        return false;
    }

    // 4. 获取查询结果
    bool found = false;
    while (query.next())
    {
        userId = query.value("user_id").toInt();
        friendId = query.value("friend_id").toInt();
        alias = query.value("alias").toString();
        found = true;
    }
    // 没有结果集，直接返回false
    if (!found)
    {
        dbPool->ReleaseConnection(db);
        return false; // 如果没有任何记录，返回 false
    }

    // 5. 执行成功，返回true
    dbPool->ReleaseConnection(db);
    return true;
}

bool DataAccessor::insertFriendship(const int& userId, const int& friendId, QString& alias)
{
    // 获取连接池实例及数据库连接
    auto dbPool = DBConnectionPool::GetInstance();
    QSqlDatabase db = dbPool->AcquireConnection();

    // 1. 直接判断数据库是否打开
    if (!db.isOpen())
    {
        dbPool->ReleaseConnection(db);
        return false;
    }

    // 2. 准备查询语句
    QSqlQuery query(db);
    query.prepare("insert into friendships (user_id, friend_id, alias) "
                  "value (:userId, :friendId, :alias)");
    query.bindValue(":userId", userId);
    query.bindValue(":friendId", friendId);
    query.bindValue(":alias", alias);


    // 3. 执行查询
    if (!query.exec())
    {
        qWarning() << "Query execution failed:" << query.lastError().text();
        dbPool->ReleaseConnection(db);
        return false;
    }

    dbPool->ReleaseConnection(db);
    return true;
}

// 在好友关系表中，查找user发送出去并且审核完成的记录
bool DataAccessor::findAllNewFriendApplicationResults(const int& userId,
                                               QVector<FinishedFriendApplicationQueryResult>& results)
{
    // 获取连接池实例及数据库连接
    auto dbPool = DBConnectionPool::GetInstance();
    QSqlDatabase db = dbPool->AcquireConnection();

    // 1. 直接判断数据库是否打开
    if (!db.isOpen())
    {
        dbPool->ReleaseConnection(db);
        return false;
    }

    // 2. 准备查询语句
    QSqlQuery query(db);
    query.prepare(" select friend_id, status, id from friendship_verify_info "
                  " where user_id = :userId and (status = 2 or status = 3);");
    query.bindValue(":userId", userId);


    // 3. 执行查询
    if (!query.exec())
    {
        qWarning() << "Query execution failed:" << query.lastError().text();
        dbPool->ReleaseConnection(db);
        return false;
    }

    // 4. 获取查询结果
    while (query.next())
    {
        FinishedFriendApplicationQueryResult record;
        record.friendId = query.value("friend_id").toInt();
        record.id = query.value("id").toInt();
        record.status = query.value("status").toInt();
        results.append(record);
    }


    dbPool->ReleaseConnection(db);
    return true;
}

// 在好友关系表中，查找好友关系记录
bool DataAccessor::findFriendshipRecordBy2Id(const int& userId, const int& friendId, FriendshipQueryResult& result)
{
    // 获取连接池实例及数据库连接
    auto dbPool = DBConnectionPool::GetInstance();
    QSqlDatabase db = dbPool->AcquireConnection();

    // 1. 直接判断数据库是否打开
    if (!db.isOpen())
    {
        dbPool->ReleaseConnection(db);
        return false;
    }

    // 2. 准备查询语句
    QSqlQuery query(db);
    query.prepare(" select f.alias, f.created_time, usi.nickname "
                  " from friendships as f "
                  " inner join user_static_info as usi on f.friend_id = usi.user_id "
                  " where f.user_id = :userId and f.friend_id = :friendId and f.status >= 0;");
    query.bindValue(":userId", userId);
    query.bindValue(":friendId", friendId);


    // 3. 执行查询
    if (!query.exec())
    {
        qWarning() << "Query execution failed:" << query.lastError().text();
        dbPool->ReleaseConnection(db);
        return false;
    }

    // 4. 获取查询结果
    bool found = false;
    while (query.next())
    {
        result.nickname = query.value("nickname").toString();
        result.alias = query.value("alias").toString();
        result.createTime = query.value("created_time").toDateTime();
        found = true;
    }
    if (!found)
    {
        dbPool->ReleaseConnection(db);
        return false;
    }

    dbPool->ReleaseConnection(db);
    return true;
}

// 在聊天缓存表中，存储聊天记录
bool DataAccessor::insertChatMsg(const int& senderId, const int& receiverId,
                                 const QString& chatMsg, int& uniqueId)
{
    // 获取连接池实例及数据库连接
    auto dbPool = DBConnectionPool::GetInstance();
    QSqlDatabase db = dbPool->AcquireConnection();

    // 1. 直接判断数据库是否打开
    if (!db.isOpen())
    {
        dbPool->ReleaseConnection(db);
        return false;
    }

    // 2. 准备查询语句
    QSqlQuery query(db);
    query.prepare("insert into chat_buffer (sender_id, receiver_id, chat_msg) "
                  "value (:senderId, :receiverId, :chatMsg)");
    query.bindValue(":senderId", senderId);
    query.bindValue(":receiverId", receiverId);
    query.bindValue(":chatMsg", chatMsg);


    // 3. 执行sql语句
    if (!query.exec())
    {
        qWarning() << "Query execution failed:" << query.lastError().text();
        dbPool->ReleaseConnection(db);
        return false;
    }

    // 4. 执行获取id语句
    query.exec("SELECT LAST_INSERT_ID()");
    if (query.next()) {
        uniqueId = query.value(0).toInt();
        qDebug() << "Last insert ID:" << uniqueId;
    }

    dbPool->ReleaseConnection(db);
    return true;
}

// 在聊天缓存表中，根据某个receiverId查询所有聊天消息
bool DataAccessor::findAllNewChatMsg(const int& receiverId, QVector<NewChatMsgQueryResult>& results)
{
    // 获取连接池实例及数据库连接
    auto dbPool = DBConnectionPool::GetInstance();
    QSqlDatabase db = dbPool->AcquireConnection();

    // 1. 直接判断数据库是否打开
    if (!db.isOpen())
    {
        dbPool->ReleaseConnection(db);
        return false;
    }

    // 2. 准备查询语句
    QSqlQuery query(db);
    query.prepare(" select sender_id, chat_msg, send_time, id from chat_buffer "
                  " where receiver_id = :receiverId and status = 0;");
    query.bindValue(":receiverId", receiverId);


    // 3. 执行查询
    if (!query.exec())
    {
        qWarning() << "Query execution failed:" << query.lastError().text();
        dbPool->ReleaseConnection(db);
        return false;
    }

    // 4. 获取查询结果
    while (query.next())
    {
        NewChatMsgQueryResult record;
        record.senderId = query.value("sender_id").toInt();
        record.msg = query.value("chat_msg").toString();
        record.sendTime = query.value("send_time").toDateTime();
        record.id = query.value("id").toInt();
        results.append(record);
    }


    dbPool->ReleaseConnection(db);
    return true;
}

// 在聊天消息缓存表中，根据id更新聊天消息的转发状态
bool DataAccessor::updateChatMsgStatusById(const int& id, const int& status)
{
    // 获取连接池实例及数据库连接
    auto dbPool = DBConnectionPool::GetInstance();
    QSqlDatabase db = dbPool->AcquireConnection();

    // 1. 直接判断数据库是否打开
    if (!db.isOpen())
    {
        dbPool->ReleaseConnection(db);
        return false;
    }

    // 2. 准备查询语句
    QSqlQuery query(db);
    query.prepare("update chat_buffer set status = :status "
                  "where id = :id;");
    query.bindValue(":status", status);
    query.bindValue(":id", id);


    // 3. 执行查询
    if (!query.exec())
    {
        qWarning() << "Query execution failed:" << query.lastError().text();
        dbPool->ReleaseConnection(db);
        return false;
    }


    dbPool->ReleaseConnection(db);
    return true;
}
